HttpClient的两种重试机制

您所在的位置:网站首页 下载器异常 点击重试 HttpClient的两种重试机制

HttpClient的两种重试机制

2024-07-14 10:15| 来源: 网络整理| 查看: 265

本文基于 HttpClient 4.5.13

使用 http 请求外部服务时,由于网络或者服务本身的不稳定性,经常需要重试。重试当然可以通过手撸代码实现,但更好的方式是通过现有的机制去实现。 HttpClient 中支持两种重试:

异常重试。 服务不可用重试。 异常重试 HttpClient 执行时会抛出两种异常:

java.io.IOException ClientProtocolException

java.io.IOException 被认为是非致命性且可恢复的,而 ClientProtocolException 被认为是致命性的,不可恢复。

处理的时候要注意, ClientProtocolException 是 java.io.IOException 的子类。

如果是这样创建 HttpClient 的

CloseableHttpClient httpClient = HttpClients.custom().build();

异常重试是默认开启的,具体代码可以参考 HttpClientBuilder.build() 方法,下面是相关的代码

// Add request retry executor, if not disabled if (!automaticRetriesDisabled) { HttpRequestRetryHandler retryHandlerCopy = this.retryHandler; if (retryHandlerCopy == null) { retryHandlerCopy = DefaultHttpRequestRetryHandler.INSTANCE; } execChain = new RetryExec(execChain, retryHandlerCopy); }

automaticRetriesDisabled 是一个 boolean 类型的变量,默认为 false ,所以条件默认是成立的,如果没有设置 HttpRequestRetryHandler 就会用一个默认的。

DefaultHttpRequestRetryHandler 主要有三个成员变量

retryCount requestSentRetryEnabled nonRetriableClasses

默认的实例变量设置如下

retryCount=3 ,最多重试3次。 requestSentRetryEnabled=false ,发送成功的就不会重试了 nonRetriableClasses 包含了以下四种:InterruptedIOException UnknownHostException ConnectException SSLException 重试的执行逻辑在 org.apache.http.impl.execchain.RetryExec ,有兴趣的可以去看下。

默认的是否重试逻辑如下

@Override public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) { Args.notNull(exception, "Exception parameter"); Args.notNull(context, "HTTP context"); if (executionCount > this.retryCount) { // Do not retry if over max retry count // 超过重试次数不重试 return false; } // 如果是忽略的异常不重试 if (this.nonRetriableClasses.contains(exception.getClass())) { return false; } for (final Class


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3